import React, {useState, useEffect} from 'react'
import {connect} from 'react-redux'
import {createForm} from 'rc-form'
import {log} from "../../../../utils/commonfunc"

// layout
import GoBackLayout from "../../../../layouts/GoBackLayout/GoBackLayout"
// icon
import VerifyIcon from "../../../../res/images/web/userinfo/ID card@2x.png"

// antd mobile
import {Icon, InputItem, List, Toast, WhiteSpace, WingBlank,} from "antd-mobile"
import CustomButton from "../../../../shared-components/CustomButton/CustomBotton"
import FormCodeInput from "../../../../shared-components/FormCodeInput/FormCodeInput"
import './RealInfo.css'
import LocalStorageService from "../../../../utils/LocalStorageService";
import {getYZMReq} from "../../../../apis/goApis";

const RealInfoForm = (props) => {
    const {
        userDetail,
        history,
        form: {getFieldProps, validateFields},
    } = props

    useEffect(() => {
        if (userDetail.initFlag === 0) {
            const uid = LocalStorageService.get('userid')
            props.fetchUserDetail({uid,})
        }
    }, [])

    const [code, setCode,] = useState('')
    const [realName, setRealName] = useState('')
    const [idNumber, setIdNumber] = useState('')
    const mobile = userDetail.Mobile
    // const [mobile, setMobile] = useState('')
    const [codeBtnActive, setCodeBtnActive] = useState(true)
    const [codeSend, setCodeSend] = useState(false)

    // props

    const {
        Realname,
        Idnumber,
    } = userDetail
    // dispatch
    const {
        emitError,
        realInfoVerify,
    } = props
    const onChange = (e, type) => {

        const o = {
            code: setCode,
            mobile: () => {},
            idNumber: setIdNumber,
            realName: setRealName,
        }

        let v
        if (type === 'code') {
            v = e.target.value
        } else {
            v = e
            if (mobile.length > 0 && idNumber.length > 0 && realName.length > 0) {
                setCodeBtnActive(true)
            }
            if (mobile.length === 0 || idNumber.length === 0 || realName.length === 0 || v.length === 0) {
                setCodeBtnActive(false)
            }
        }
        o[type](v)
    }
    // isVerify
    const isVerify = userDetail.Realname ? true : false
    // const isVerify = false

    const checkBeforeSubmit = (vals) => {
        const mapper = {
            realName: '姓名',
            idNumber: '身份证号码',
            mobile: '手机号码',
            code: '验证码',
        }

        for (let key in vals) {
            let val = vals[key]
            log(val)
            if (val === undefined || val === '') {
                emitError(`${mapper[key]}不能为空`)
                return false
            }
        }
        return true
    }

    const onCodeBtnClick = () => {
        getYZMReq({mobile, style: 4,})
            .then((res) => {
                if (res.data.ok) {
                    Toast.info('验证码已发送')
                    setCodeSend(true)
                    setCodeBtnActive(false)
                }
            })

    }

    const submit = async () => {
        const uid = localStorage.getItem('userid')
        const vals = {uid, mobile, realName,idNumber, code,}
        if (checkBeforeSubmit(vals)) {
            const resp = await realInfoVerify(vals)
            if (resp.data.ok) {
                props.onSuccess && await props.onSuccess()
            }
        }
    }
    //
    const nameInputTemplate = (
        <InputItem
            {...getFieldProps('realName')}
            onChange={e => onChange(e, 'realName')}
            value={realName}
            placeholder='请输入您的姓名'
        >
            <span>姓名</span>
        </InputItem>
    )


    const IDCardInputTemplate = (
        <InputItem
            {...getFieldProps('idNumber')}
            value={idNumber}
            onChange={e => onChange(e, 'idNumber')}
            placeholder='请输入您的身份证号码'

        >
            <span>身份证号码</span>
        </InputItem>
    )


    const mobileInputTemplate = (
        <InputItem
            {...getFieldProps('mobile')}
            // type="phone"
            placeholder="请输入有效手机号码"
            value={mobile}
            onChange={e => onChange(e, 'mobile')}
        >
            <span>手机号码</span>
        </InputItem>
    )

    const codeInputTemplate = (
        <div style={{width: '100%', backgroundColor: '#fff'}}>
            <WingBlank>
                <FormCodeInput
                    codeBtnActive={codeBtnActive}
                    setCodeBtnActive={setCodeBtnActive}
                    text='text'
                    value={code}
                    onChange={e => onChange(e, 'code')}
                    placeholder='请输入验证码'
                    onCodeBtnClick={onCodeBtnClick}
                    codeSend={codeSend}

                />
            </WingBlank>
        </div>
    )

    const infoTemplate = (
        <div className='real-info-tips'>
            <p>提示：</p>
            <p>1、1个设备，10分钟内只能获取1次验证码</p>
            <p>2、实名认证提交后，不能修改，平台将对您的资料严格保密</p>
            <p>3、非中国大陆公民或实名认证遇到问题，请联系客服；QQ123456789</p>
        </div>
    )
    // 未验证用户模板
    const verifyTemplate = (
        <>
            <WhiteSpace />
            <List>
                {nameInputTemplate}
                {IDCardInputTemplate}
            </List>
            <WhiteSpace />
            <List>
                {mobileInputTemplate}
                {codeInputTemplate}
            </List>
            <WhiteSpace/>
            <WingBlank>
                {infoTemplate}
                <div>
                    <CustomButton
                        onClick={submit}
                        shadow='0px 6px 10px 0px rgba(33, 58, 75),0.4)'
                    >提交</CustomButton>
                </div>
            </WingBlank>
        </>
    )
    // 验证用户模板
    const successTemplate = (
        <WingBlank>
            <div className='real-info-success'>
                <div>
                    <img src={VerifyIcon} alt='' style={{width: 109, height: 78,}}/>
                    <div className='real-info-success-upper'>
                        <div className='real-info-success-upper-checked'>
                            <Icon type='check' color='#fff'/>
                        </div>
                        <p>您已完成实名验证</p>
                    </div>
                </div>
                <div>
                    <div className='flex-space-between'>
                        <p>姓名</p><p>{Realname}</p>
                    </div>
                    <WhiteSpace/>
                    <div className='flex-space-between'>
                        <p>身份证号</p><p>{Idnumber}</p>
                    </div>
                </div>
            </div>
            <CustomButton
                onClick={() => {history.goBack()}}
                shadow='0px 6px 10px 0px rgba(33, 58, 75),0.4)'
            >返回</CustomButton>
        </WingBlank>
    )
    return isVerify? successTemplate : verifyTemplate
}

const mapStateToProps = ({user: {userdetail,},}) => ({
    userDetail: userdetail,
})

const mapDispatchToProps = ({global: {globalError,}, user: {doRealInfoVerify, fetchUserDetail},}) => ({
    emitError: (err) => globalError(err),
    realInfoVerify: (payload) => doRealInfoVerify(payload),
    fetchUserDetail: (paylaod) => fetchUserDetail(paylaod),
})

export default connect(
    mapStateToProps,
    mapDispatchToProps,
)(createForm()(RealInfoForm))
